import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../function/model/chat_group_model.dart';
import '../../../function/model/chat_message_model.dart';
import '../../../function/model/user_model.dart';
import '../../../function/state/chat_group_state.dart';
import '../../../function/state/chat_message_state.dart';
import '../../../function/state/user_state.dart';
import '../../../function/utils/my_common.dart';
import '../../../function/widgets/custom_snackbar.dart';
import '../../../function/widgets/login_dialog_widget.dart';
import '../../../function/widgets/report_dialog.dart';

/// 群聊聊天页面控制器
/// 使用非常规命名避免标准模式
class GroupChatController extends GetxController {
  final ChatGroupState _chatGroupState = Get.find<ChatGroupState>();
  final ChatMessageState _chatMessageState = Get.find<ChatMessageState>();
  final UserState _userState = Get.find<UserState>();

  final TextEditingController _messageController = TextEditingController();
  final FocusNode _messageFocusNode = FocusNode();

  // 当前群聊
  final Rx<ChatGroupModel?> _currentGroup = Rx<ChatGroupModel?>(null);

  // 是否正在发送消息
  final RxBool _isSending = false.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeController();
  }

  @override
  void onClose() {
    _messageController.dispose();
    _messageFocusNode.dispose();
    super.onClose();
  }

  /// 初始化控制器
  void _initializeController() {
    // 获取传递的群聊参数
    final arguments = Get.arguments;
    if (arguments is ChatGroupModel) {
      _currentGroup.value = arguments;
      _setupChatEnvironment();
    }
  }

  /// 设置聊天环境
  void _setupChatEnvironment() {
    if (_currentGroup.value == null) return;

    // 设置当前群聊ID
    _chatMessageState.setCurrentGroupId(_currentGroup.value!.id);

    // 设置当前用户ID
    if (_userState.isLoggedIn && _userState.currentUser != null) {
      _chatMessageState.setCurrentUserId(_userState.currentUser!.id);
    }
  }

  /// 获取当前群聊
  ChatGroupModel? get currentGroup => _currentGroup.value;

  /// 获取消息控制器
  TextEditingController get messageController => _messageController;

  /// 获取焦点节点
  FocusNode get messageFocusNode => _messageFocusNode;

  /// 是否正在发送消息
  bool get isSending => _isSending.value;

  /// 获取当前群聊的消息
  List<ChatMessageModel> getCurrentGroupMessages() {
    if (_currentGroup.value == null) return [];
    return _chatMessageState.getGroupMessages(_currentGroup.value!.id);
  }

  /// 检查是否为当前用户
  bool isCurrentUser(String senderId) {
    if (!_userState.isLoggedIn || _userState.currentUser == null) {
      return false;
    }
    return senderId == _userState.currentUser!.id;
  }

  /// 根据ID获取用户
  UserModel? getUserById(String userId) {
    return _userState.getUserById(userId);
  }

  /// 获取当前用户头像
  String getCurrentUserAvatar() {
    if (!_userState.isLoggedIn || _userState.currentUser == null) {
      return 'assets/images/avatar1.png';
    }
    return _userState.currentUser!.avatar;
  }

  /// 发送消息
  void sendMessage() {
    final content = _messageController.text.trim();
    if (content.isEmpty || _currentGroup.value == null) return;

    // 检查用户是否已登录
    if (!_userState.isLoggedIn) {
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    // 检查用户是否已加入群聊
    final bool hasJoined =
        _chatGroupState
            .getGroupById(_currentGroup.value!.id)
            ?.isUserJoined(_userState.currentUser!.id) ??
        false;
    if (!hasJoined) {
      CustomSnackBar.warning('You need to join this group first');
      return;
    }

    // 发送消息
    _isSending.value = true;
    _chatMessageState.sendTextMessage(_currentGroup.value!.id, content);
    _messageController.clear();
    _isSending.value = false;
  }

  /// 显示群聊选项
  void showGroupOptions() {
    if (_currentGroup.value == null) return;

    Get.bottomSheet(
      Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: MyCommonUtils.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r),
            topRight: Radius.circular(20.r),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 群聊信息
            _buildGroupInfo(),

            SizedBox(height: 20.h),

            // 选项列表
            _buildOptionsList(),
          ],
        ),
      ),
      isScrollControlled: true,
    );
  }

  /// 举报当前群聊：弹出举报弹窗，提交后清空该群聊消息并返回上一页
  void reportCurrentGroup() {
    if (_currentGroup.value == null) return;

    ReportDialogUtils.showReportDialog(
      onReportSubmitted: (String reportType) {
        // 清空该群聊的所有消息
        _chatMessageState.clearGroupMessages(_currentGroup.value!.id);
        // 返回上一页（退出聊天页面）
        Get.back();
      },
    );
  }

  /// 构建群聊信息
  Widget _buildGroupInfo() {
    final group = _currentGroup.value!;
    return Row(
      children: [
        CircleAvatar(
          radius: 30.w,
          backgroundImage: AssetImage(group.coverImage),
        ),
        SizedBox(width: 16.w),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                group.title,
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w700,
                  color: MyCommonUtils.black,
                ),
              ),
              SizedBox(height: 4.h),
              Text(
                '${group.memberCount} members',
                style: TextStyle(fontSize: 14.sp, color: MyCommonUtils.grey),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建选项列表
  Widget _buildOptionsList() {
    return Column(
      children: [
        _buildOptionItem(
          icon: Icons.info_outline,
          title: 'Group Info',
          onTap: () {
            Get.back();
            // TODO: 显示群聊详情
          },
        ),
        _buildOptionItem(
          icon: Icons.people_outline,
          title: 'Members',
          onTap: () {
            Get.back();
            // TODO: 显示成员列表
          },
        ),
        _buildOptionItem(
          icon: Icons.settings_outlined,
          title: 'Settings',
          onTap: () {
            Get.back();
            // TODO: 显示群聊设置
          },
        ),
      ],
    );
  }

  /// 构建选项项
  Widget _buildOptionItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: MyCommonUtils.blue),
      title: Text(
        title,
        style: TextStyle(fontSize: 16.sp, color: MyCommonUtils.black),
      ),
      onTap: onTap,
    );
  }
}
